﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EntityComponentSystem.Framework.Json
{
    public class JsonArray : JsonValue, IJsonArray, IEnumerable<JsonValue>
    {
        private List<JsonValue> items = new List<JsonValue>();

        public JsonArray()
        {

        }

        public JsonArray(params JsonValue[] values)
        {
            if (values != null && values.Length > 0)
            {
                foreach (var v in values)
                    this.Add(v);
            }
        }

        public override void Write(StringBuilder sb)
        {
            sb.Append('[');
            var first = true;
            foreach (var i in items)
            {
                if (!first)
                    sb.Append(',');

                i.Write(sb);

                first = false;
            }
            sb.Append(']');
        }

        public int Count { get { return items.Count; } }

        public void Add(object value)
        {
            if (value is JsonValue)
                items.Add((JsonValue)value);
            else
                items.Add(JsonValue.GetValue(value));
            
            //items.Add(new JsonInstance(value));
        }

        public JsonValue this[int index]
        {
            get
            {
                if (index < 0 || index >= items.Count)
                    throw new ArgumentOutOfRangeException("index");
                return items[index];
            }
            set
            {
                if (index < 0 || index >= items.Count)
                    throw new ArgumentOutOfRangeException("index");
                items[index] = value;
            }
        }

        public override JsonTypes Type { get { return JsonTypes.Array; } }

        public override string ToString()
        {
            var sb = new StringBuilder();
            Write(sb);
            return sb.ToString();
        }

        public IEnumerator<JsonValue> GetEnumerator()
        {
            foreach (var item in items)
                yield return item;
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            foreach (var item in items)
                yield return item;
        }
    }

}
